//To-do: remove
#include <stdio.h>

/**
 * AppleIIGo
 * Internal Memory Expansion class
 * (C) 2008 by Marc S. Ressl (mressl@umich.edu)
 * Released under the GPL
 */

#include "InternalMemoryExpansion.h"

InternalMemoryExpansion::InternalMemoryExpansion(Motherboard * motherboard,
												 char * slotDeviceName) :
SlotDevice(motherboard, slotDeviceName) {
}

void InternalMemoryExpansion::onMemoryRequested() {
	ramMemoryOffset = motherboard->getMemory()->
		requestMemory(INTERNALMEMORYEXPANSION_BYTENUM);
}

void InternalMemoryExpansion::onMemoryAllocated() {
	ramMemory = motherboard->getMemory()->getMemory(ramMemoryOffset);
}

void InternalMemoryExpansion::onResetAsserted(bool isRestart) {
	ramMemoryIndex = 0;
	
	if (!isRestart)
		return;
	
	for (UINT32 index = 0; index < INTERNALMEMORYEXPANSION_BYTENUM; index++)
		ramMemory[index] = 0;
}

void InternalMemoryExpansion::writeIo(UINT16 address, UINT8 value) {
	switch (address & 0x3) {
		case 0:
			ramMemoryIndex = (ramMemoryIndex & 0xffff00) | (value << 0);
			break;
		case 1:
			ramMemoryIndex = (ramMemoryIndex & 0xff00ff) | (value << 8);
			break;
		case 2:
			ramMemoryIndex = (ramMemoryIndex & 0x00ffff) | (value << 16);
			break;
		case 3:
			ramMemoryIndex &= (INTERNALMEMORYEXPANSION_BYTENUM - 1);
			ramMemory[ramMemoryIndex++] = value;
			ramMemoryIndex &= (INTERNALMEMORYEXPANSION_BYTENUM - 1);
			break;
	}
}

UINT8 InternalMemoryExpansion::readIo(UINT16 address) {
	UINT8 value;
	
	switch (address & 0x3) {
		case 0:
			value = (ramMemoryIndex >> 0) & 0xff;
			break;
		case 1:
			value = (ramMemoryIndex >> 8) & 0xff;
			break;
		case 2:
			value = ((ramMemoryIndex >> 16) & 0xff) | 0xf0;
			break;
		case 3:
			ramMemoryIndex &= (INTERNALMEMORYEXPANSION_BYTENUM - 1);
			value = ramMemory[ramMemoryIndex++];
			ramMemoryIndex &= (INTERNALMEMORYEXPANSION_BYTENUM - 1);
			break;
	}
	
	return value;
}
